package thread.ReentrantLock;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ProducerAndConsumer  {
    static List<String> list  = new ArrayList<String>();
    static ReentrantLock reentrantLock = new ReentrantLock();
    static Condition condition = reentrantLock.newCondition();

    public static void main(String[] args) {
        Thread producer = new Thread(new Producer(),"生产者");
        Thread consumer = new Thread(new Consumer(),"消费者");
        producer.start();
        consumer.start();

    }
}

class Producer implements  Runnable{


    @Override
    public void run() {

        try {
            ProducerAndConsumer.reentrantLock.lock();
            while (true) {
                TimeUnit.SECONDS.sleep(1);
                if (ProducerAndConsumer.list.size() < 10) {
                    System.out.println(Thread.currentThread().getName() + ":生产物资");
                    ProducerAndConsumer.list.add(Thread.currentThread().getName() + ":生产物资");
                } else {
                    System.out.println(Thread.currentThread().getName() + ":仓库已满");
                    ProducerAndConsumer.condition.signal();
                    ProducerAndConsumer.condition.await();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ProducerAndConsumer.reentrantLock.unlock();
        }

    }
}

class Consumer implements Runnable{


    @Override
    public void run() {
        try {
            ProducerAndConsumer.reentrantLock.lock();
            while (true) {
                TimeUnit.SECONDS.sleep(1);

                if (ProducerAndConsumer.list.size() > 0) {
                    System.out.println(Thread.currentThread().getName() + ":消费物资");
                    ProducerAndConsumer.list.remove(0);
                } else {
                    System.out.println(Thread.currentThread().getName() + ":物资短缺");
                    ProducerAndConsumer.condition.signal();
                    ProducerAndConsumer.condition.await();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            ProducerAndConsumer.reentrantLock.unlock();
        }

    }
}
